package cn.kgc.shiro.controller;

import cn.kgc.shiro.entity.User;
import cn.kgc.shiro.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 课工场
 * @date 2024/3/26
 * @description
 */
@RestController
@RequestMapping("user")
public class UserController {

    @Resource
    private UserService userService;


    @GetMapping("toLogin")
    public Map<String, Object> toLogin() {
        HashMap<String, Object> result = new HashMap<>();
        result.put("code", 401);
        result.put("msg", "请认证后访问");
        return result;
    }

    @GetMapping("login")
    public Map<String, Object> login(String username, String password) {
        HashMap<String, Object> result = new HashMap<>();

        // 通过subject主体 完成认证
        Subject subject = SecurityUtils.getSubject();
        // 将前端传递的用户名和密码进行数据的封装  UsernamePasswordToken
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
        // 只要没有异常则认证通过
        subject.login(usernamePasswordToken);
        result.put("code", 200);
        result.put("message", "认证通过");
        return result;
    }

    //  logical = Logical.OR  设置多个角色之间的逻辑关系
    @RequiresRoles(value = {"admin", "customer"}, logical = Logical.OR)
    @GetMapping("list")
    public List<User> getUserList() {
        return userService.list();
    }


    @RequiresRoles("admin")
    @GetMapping("/delete/{id}")
    public boolean delete(@PathVariable("id") Integer id) {

        return userService.removeById(id);
    }

}
